package com.example.batch.dbconfig;

import com.example.batch.utils.Utils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration("batchMybatisConfig")
@AutoConfigureAfter(BatchDataSourceConfig.class)
public class BatchMybatisConfig {

    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("batchDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("batchSqlFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("batchDataSource") DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:/mapper/batch/*.xml"));
            sqlSessionFactoryBean.setPlugins(new Interceptor[]{Utils.resetPageHelper("mysql")});
            return sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MybatisConfig.sqlSessionFactoryBean(): error !");
        }
    }

    @Bean("batchSqlTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("batchSqlFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("batchMapperScan")
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setSqlSessionFactoryBeanName("batchSqlFactory");
        scannerConfigurer.setBasePackage("com.example.batch.**.mapper.batch");
        return scannerConfigurer;
    }
}
